package br.com.timecardforpeon.dialog;

import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import br.com.timecardforpeon.R;
import br.com.timecardforpeon.domain.Entry;
import br.com.timecardforpeon.event.EventPublisher;
import br.com.timecardforpeon.event.impl.RemoveEntryEvent;
import br.com.timecardforpeon.exception.TimeCardException;
import br.com.timecardforpeon.sqlite.domain.EntryDao;
import br.com.timecardforpeon.util.Util;

public class RemoveDialog extends Dialog {

	private Entry entry;
	private EntryDao dao;
	
	private EventPublisher publisher = new EventPublisher();

	private Button yesButton;
	private Button noButton;

	public RemoveDialog(Context context, Entry entry) {
		super(context);
		
		this.setContentView(R.layout.remove_dialog);
		this.setTitle(R.string.remove);

		this.entry = entry;

		this.dao = new EntryDao(context);

		this.initializeComponents();
		this.initializeListeners();
	}

	private void initializeComponents() {
		this.yesButton = Util.<Button> getViewById(this, R.id.yesButton);
		this.noButton = Util.<Button> getViewById(this, R.id.noButton);
	}

	private void initializeListeners() {
		this.yesButton.setOnClickListener(new YesClickListener(this));
		this.noButton.setOnClickListener(new NoClickListener(this));
	}

	private final class YesClickListener implements android.view.View.OnClickListener {

		private Dialog dialog;

		public YesClickListener(Dialog dialog) {
			this.dialog = dialog;
		}

		@Override
		public void onClick(View v) {

			Context context = getContext();

			try {
				
				dao.delete(entry);
				this.dialog.dismiss();
				publisher.publish(new RemoveEntryEvent(entry));
				
			} catch (TimeCardException e) {
				Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
			}
		}
	}

	private final class NoClickListener implements android.view.View.OnClickListener {

		private Dialog dialog;

		public NoClickListener(Dialog dialog) {
			this.dialog = dialog;
		}

		@Override
		public void onClick(View view) {
			this.dialog.dismiss();
		}
	}
}